package com.basketball.gym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basketball.gym.mapper.InformationMapper;
import com.basketball.gym.mapper.UserMapper;
import com.basketball.gym.pojo.*;
import com.basketball.gym.pojo.state.ResponseState;
import com.basketball.gym.service.AdminUserService;
import com.basketball.gym.utils.WrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private InformationMapper informationMapper;

    /**
     * 获取用户列表
     */
    @Override
    public ResponseData<IPage<User>> getUserList(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user.getState() != null) {
            queryWrapper.eq("state", user.getState());
        }
        if (user.getId() != null) {
            queryWrapper.eq("id", user.getId());
        }
        if (user.getPhone() != null) {
            queryWrapper.eq("phone", user.getPhone());
        }
        Page<User> userPage = new Page<>();
        if (user.getCurrent() != null && user.getSize() != null) {
            userPage = new Page<>(user.getCurrent(), user.getSize());
        }
        IPage<User> userIPage = userMapper.selectPage(userPage, queryWrapper);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), userIPage);

    }

    /**
     * 修改用户信息
     */
    @Override
    @Transactional
    public ResponseData<User> updateUser(User user) {
        userMapper.updateById(user);
        if (user.getInformation() != null) {
            Information information = informationMapper.selectOne(WrapperUtils.getOneEqQueryWrapper("user_id", user.getId()));
            user.getInformation().setUserId(user.getId());
            if (information == null) {
                informationMapper.insert(user.getInformation());
            } else {
                user.getInformation().setId(information.getId());
                informationMapper.updateById(user.getInformation());
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 通过手机号查询用户
     */
    @Override
    public ResponseData<User> getUserByPhone(String phone) {
        User user=userMapper.selectOne(WrapperUtils.getOneEqQueryWrapper("phone",phone));
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(),user);
    }
}
